﻿using AuthCenter.Api.Read.Application.Command.RoleMenu;
using AuthCenter.Api.Read.Application.Output;
using AuthCenter.Application;
using AuthCenter.Domain;
using AuthCenter.ErrorCode;
using MediatR;
using System.Security.Cryptography;

namespace AuthCenter.Api.Read.Application.Hander.RoleMenu
{
    public class GetUserRoleMenuHander:IRequestHandler<GetUserRoleMenuCommand,ApiResult<List<UserRoleMenuOutput>>>
    {
        private readonly IBaseRepository<RoleMenuModel> _rolemenuRepository;
        private readonly IBaseRepository<MenuModel> _menuRepository;
        public GetUserRoleMenuHander(IBaseRepository<RoleMenuModel> roleRepository, IBaseRepository<MenuModel> menuRepository)
        {
            _rolemenuRepository = roleRepository;
            _menuRepository = menuRepository;
        }
        /// <summary>
        /// 根虎角色ID查询菜单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<UserRoleMenuOutput>>> Handle(GetUserRoleMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<UserRoleMenuOutput>> res = new ApiResult<List<UserRoleMenuOutput>>();
            var list=request.RoleId.Split(",").ToList();
            var rolemenuQuery = _rolemenuRepository.GetAll();
            List<long> model = new List<long>();
            foreach (var item in list) 
            {
                var mids = rolemenuQuery.Where(x => x.RId == Convert.ToInt64(item)).Select(x => x.MId).ToList();
                model.AddRange(mids);
            }
            var menuQuery = _menuRepository.GetAll().Where(x => !x.IsDeleted);
            var data = Find(0, menuQuery.ToList(), model);
            res.Code=ApiEnums.OK;
            res.Message = "成功";
            res.Data = data;
            return Task.FromResult(res);
        }
        private List<UserRoleMenuOutput> Find(long id, List<MenuModel> ids, List<long> mid) 
        {
            var res=ids.Where(x=>x.PId==id&&mid.Contains(x.Id)).ToList();
            List<UserRoleMenuOutput> menus=new List<UserRoleMenuOutput>();
            foreach (var item in res)
            {
                menus.Add(new UserRoleMenuOutput 
                {
                 
                    MenuName=item.MenuName,
                    Url=item.Url,
                    Children = Find(item.Id, ids, mid)
                });
            }
            return menus;
        }
    }
}
